package com.demo.shiro.test;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

public class HelloWorld {

	public static void main(String[] args) {
		// 读取配置文件
		SecurityManager securityManager = getInstanceByFactory(new IniSecurityManagerFactory("classpath:shiro.ini"));
		// 绑定 SecurityManager
		SecurityUtils.setSecurityManager(securityManager);
		// 获取当前用户
		Subject currentUser = SecurityUtils.getSubject();
		if (!currentUser.isAuthenticated()) {
			try {
				// 创建 token
				UsernamePasswordToken token = new UsernamePasswordToken("admin", "123");
				// 登录
				currentUser.login(token);
				System.out.println("登录成功.");
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("登录失败.");
			}
		}
		// 退出
		currentUser.logout();
	}

	// 获得实例
	static <T> T getInstanceByFactory(Factory<T> f) {
		return f.getInstance();
	}
}
